package com.hsgene.product.controller;

import com.hsgene.common.ClientType;
import com.hsgene.common.util.exception.CommonErrorCode;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.OrderHelper;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.product.condition.PackageCondition;
import com.hsgene.product.domain.GeneticTestingPackage;
import com.hsgene.product.dto.GeneticTestingPackageDto;
import com.hsgene.product.dto.PackageDetilOrgsDto;
import com.hsgene.product.dto.QuerySetMealDto;
import com.hsgene.product.dto.peanut.GeneticTestingPackageDetilPeanutDto;
import com.hsgene.product.exception.ProductErrorCode;
import com.hsgene.product.service.ProductService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @desc:基因检测套餐管理
 * @author: fuxiang
 * @date: 2018/9/18 16:01
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/packages")
public class ProductController {
    @Autowired
    private  ProductService productService;

    /**
     * 添加基因套餐
     * @param geneticTestingPackage
     * @return
     */
    @PostMapping
    public ApiResult<GeneticTestingPackage> addProduct(@RequestBody GeneticTestingPackage geneticTestingPackage){
        return productService.addProduct(geneticTestingPackage);
    }

    /**
     * 修改基因套餐
     * @param geneticTestingPackage
     * @return
     */
    @PutMapping
    public ApiResult updateProduct(@RequestBody GeneticTestingPackage geneticTestingPackage,@FromSession UserInfo userInfo){
        //标记套餐被使用
        if(geneticTestingPackage.getIsUsed()!=null){
            return productService.updateUsed(geneticTestingPackage.getId());
        }
        if(userInfo!=null){
            geneticTestingPackage.setUserId(userInfo.getUserId());
        }
        //套餐修改
        return productService.updateProduct(geneticTestingPackage);
    }

    /**
     * 标记套餐被使用（批量）
     * @param ids  id数组
     * @return
     */
    @PutMapping("tag/use")
    public ApiResult tagPackage(@RequestBody List<String> ids){
       return productService.updateUsedMore(ids);
    }

    /**
     *修改套餐，包含机构套餐成本
     * @author FX
     * @date 2018/11/27 15:27
     * @param geneticTestingPackage
     * @param userInfo
     * @return
     */
    @PutMapping("cost")
    public ApiResult updateProductCost(@RequestBody GeneticTestingPackage geneticTestingPackage,@FromSession UserInfo userInfo){
        if(userInfo!=null){
            geneticTestingPackage.setUserId(userInfo.getUserId());
        }
        //套餐修改
        return productService.updateProduct(geneticTestingPackage);
    }

    /**
     * 判断名称是否重复
     * @param packageName
     * @return
     */
    @GetMapping("name")
    public ApiResult<GeneticTestingPackage> getByPackageId(@RequestParam("packageName") String packageName,String id){
        ApiResult<GeneticTestingPackage> byPackageName = productService.getByPackageName(packageName);
        if(StringUtils.isNotEmpty(id)){
            ApiResult<GeneticTestingPackage> packageById = productService.getPackageById(id,null);
            if(packageById.getData().getPackageName().equals(packageName)){
                return ApiResult.succ();
            }
        }
        if(byPackageName.getData()==null){
            return ApiResult.succ();
        }
        return ApiResult.fail(ProductErrorCode.PACKAGE_ALREADY_EXISTS) ;
    }

    /**
     * 根据套餐名称获取套餐
     * @param packageName
     * @return
     */
    @GetMapping("package")
    public ApiResult<GeneticTestingPackage> getByPackageName(@RequestParam("packageName") String packageName){
        return productService.getByPackageName(packageName);
    }

    /**
     * 查询套餐列表
     *
     * @return 套餐列表
     */
    @GetMapping
    public ApiResult getList(@RequestParam(name = "page" ,defaultValue = "1") Integer page
            , @RequestParam(name = "size",defaultValue = "15") Integer size, PackageCondition condition
           ) {
        condition.setLimitHelper(LimitHelper.create(page, size, true));
        condition.setOrderHelper(OrderHelper.create("c.update_date_time", false));
        condition.setPage(page);
        condition.setSize(size);
        if(ClientType.CONSOLE.getCode().equals(condition.getPlatform())){
            return productService.getList(condition);
        }else if(ClientType.PEANUT.getCode().equals(condition.getPlatform())
                ||ClientType.GOLD_COLORED_GLASS.getCode().equals(condition.getPlatform())){
            //花生仁和金琉璃
            return productService.getListPeanut(condition);
        }
        return ApiResult.fail(CommonErrorCode.CLIENT_TYPE_EXCEPTION_NOT_SUPPORTED);
    }


    /**
     * 套餐详情
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ApiResult getPackageById(@PathVariable("id") String id,Integer platform){
        if(ClientType.CONSOLE.getCode().equals(platform)){
            return productService.getPackageById(id,null);
        }else if(ClientType.PEANUT.getCode().equals(platform)){
            //花生仁
            return productService.peanutPackageDetail(id);
        }else if(ClientType.GOLD_COLORED_GLASS.getCode().equals(platform)){
           //金琉璃
            return productService.glazePackageDetail(id);
        }
        return ApiResult.fail(CommonErrorCode.CLIENT_TYPE_EXCEPTION_NOT_SUPPORTED);
    }
    /**
     * 套餐详情（包含机构检测成本）
     * @param id
     * @return
     */
    @GetMapping("/cost/{id}")
    public ApiResult getPackageByIdCost(@PathVariable("id") String id,Integer platform){
        if(ClientType.CONSOLE.getCode().equals(platform)) {
            return productService.getPackageById(id,"cost");
        }
        return ApiResult.fail(CommonErrorCode.CLIENT_TYPE_EXCEPTION_NOT_SUPPORTED);
    }
    /**
     * 删除套餐
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public ApiResult<GeneticTestingPackage> deletePackageById(@PathVariable("id") String id){
        return productService.deletePackageById(id);
    }

    /**
     * 批量删除套餐
     * @param
     * @return
     */
    @DeleteMapping
    public ApiResult<GeneticTestingPackageDto> deletePackageByIds(@RequestBody List<GeneticTestingPackageDto> condition){
        return productService.deletePackageByIds(condition);
    }

    /***
     * 花生仁查询套餐检测信息
     * @author jcl
     * @date 2019/1/8 9:51
     * @param packageId 套餐id
     * @param agencyId 机构id
     * @return
     */
    @GetMapping("products/details/{product_detail_id}/{agency_id}")
    public ApiResult packageTestingInfo(@PathVariable("product_detail_id")String packageId,
                                        @PathVariable("agency_id")String agencyId){
        try {
            return productService.packageTestingInfo(packageId,agencyId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(500,"failed","获取数据失败",e.toString());
        }
    }

    /**
     * 根据关键字查询套餐（花生仁）
     * @param
     * @return
     */
    @GetMapping("keywords")
    public ApiResult getByKeyword(Integer size,Integer page,PackageCondition condition){
        if(page!=null){
            if(page==null){
               size=10;
            }
            condition.setLimitHelper(LimitHelper.create(page, size, true));
            condition.setOrderHelper(OrderHelper.create("c.update_date_time", false));
            return productService.getByKeywordPage(condition);
        }
       return productService.getByKeyword(condition);
    }

    /**
     * 根据套餐id查找对应检测方式
     * @param id
     * @return
     */
    @GetMapping("{package_id}/products")
    public ApiResult<List<GeneticTestingPackageDetilPeanutDto>> getDetailsByPackageId(@PathVariable("package_id") String id){
        return productService.getDetailsByPackageId(id);
    }

    /**
     * 根据套餐id查找套餐下的检测机构
     * @param id
     * @return
     */
    @GetMapping("{package_id}/products/agency")
    public ApiResult<List<PackageDetilOrgsDto>> getArgsByPackageId(@PathVariable("package_id") String id){
        return productService.getArgsByPackageId(id);
    }

    /**
     * 根据sampleId查找数量
     * @param samplyId
     * @return
     */
   @GetMapping("sample/count")
   public ApiResult<Integer> getCountBySamplyId(String samplyId){
          return  productService.getCountBySamplyId(samplyId);
   }
}
